package com.example.pets;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.NavigationUI;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_CODE_PERMISSIONS = 1001;

    // 需要申请的权限列表
    private static final String[] REQUIRED_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION
    };
    private String[] permissions;
    private int requestCode;
    private LocationClient locationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BottomNavigationView bottomNav = findViewById(R.id.bottom_nav);

        NavHostFragment navHostFragment =
                (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);

        if (navHostFragment != null) {
            NavController navController = navHostFragment.getNavController();
            NavigationUI.setupWithNavController(bottomNav, navController);
        }

        checkPermissions();
    }



    private void requestAppPermissions(String[] permissions, int requestCode) {
        ActivityCompat.requestPermissions(this, permissions, requestCode);
    }
    private void checkPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionsNeeded = new ArrayList<>();

            for (String permission : REQUIRED_PERMISSIONS) {
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    permissionsNeeded.add(permission);
                }
            }

            if (!permissionsNeeded.isEmpty()) {
                // 如果是首次请求某些权限，直接请求；否则显示解释后再请求
                boolean shouldShowRationale = false;
                for (String permission : permissionsNeeded) {
                    shouldShowRationale = ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
                    if (shouldShowRationale) break;
                }

                if (shouldShowRationale) {
                    new AlertDialog.Builder(this)
                            .setTitle("需要权限")
                            .setMessage("本应用需要访问您的位置和存储空间，请允许相关权限以继续操作。")
                            .setPositiveButton("确定", (dialog, which) -> requestPermissions(permissionsNeeded.toArray(new String[0]), REQUEST_CODE_PERMISSIONS))
                            .setNegativeButton("取消", (dialog, which) -> Toast.makeText(this, "部分功能将受限", Toast.LENGTH_SHORT).show())
                            .show();
                } else {
                    requestPermissions(permissionsNeeded.toArray(new String[0]), REQUEST_CODE_PERMISSIONS);
                }
            } else {
                // 所有权限都已授予，可以执行操作
                onAllPermissionsGranted();
            }
        } else {
            // Android 6.0 以下自动拥有权限
            onAllPermissionsGranted();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_CODE_PERMISSIONS) {
            boolean allGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }

            if (allGranted) {
                // 所有权限都被授予
                onAllPermissionsGranted();
            } else {
                // 有权限被拒绝
                Toast.makeText(this, "部分权限被拒绝，功能可能受限", Toast.LENGTH_SHORT).show();
                showGoToSettingsDialog();
            }
        }
    }
    private void onAllPermissionsGranted() {
        Toast.makeText(this, "权限已全部授予", Toast.LENGTH_SHORT).show();

        // 可以在这里初始化定位、读写文件等操作
        new Thread(new Runnable() {
            @Override
            public void run() {
                initBaiduLocation();     // 初始化百度地图定位
            }
        }).start();

    }

    private void initBaiduLocation() {
        try {
            LocationClient.setAgreePrivacy(true);
            locationClient = new LocationClient(getApplicationContext());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 设置定位参数
        initLocation();
        // 注册位置监听器
        locationClient.registerLocationListener(new MyLocationListener());
        // 开始定位
        locationClient.start();
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy); // 可选，默认高精度
        option.setCoorType("bd09ll"); // 返回百度经纬度坐标系
        option.setScanSpan(1000); // 可选，默认0，即仅定位一次，设置发起连续定位请求的时间间隔
        option.setIsNeedAddress(true); // 可选，是否需要地址信息，默认不需要
        locationClient.setLocOption(option);
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        private StringBuilder currentPosition;

        @Override
        public void onReceiveLocation(BDLocation location) {
            MapApplication.location=location;
            if (location == null || location.getLocType() == BDLocation.TypeServerError) {
                return;
            }

            currentPosition = new StringBuilder();
            currentPosition.append("纬度：").append(location.getLatitude()).append('\n');
            currentPosition.append("经度：").append(location.getLongitude()).append('\n');
            currentPosition.append("国家：").append(location.getCountry()).append('\n');
            currentPosition.append("省：").append(location.getProvince()).append('\n');
            currentPosition.append("市：").append(location.getCity()).append('\n');
            currentPosition.append("区：").append(location.getDistrict()).append('\n');
            currentPosition.append("街道：").append(location.getStreet()).append('\n');

            // 在这里处理位置数据
            Log.e("====",currentPosition.toString());
        }
    }
    private void showGoToSettingsDialog() {
        new AlertDialog.Builder(this)
                .setTitle("权限未完全授予")
                .setMessage("请手动前往应用设置中开启所有必要权限。")
                .setPositiveButton("去设置", (dialog, which) -> {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivity(intent);
                })
                .setNegativeButton("取消", null)
                .show();
    }



















}

